package org.example.computerdesign.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.example.computerdesign.common.RespBody;
import org.example.computerdesign.common.enums.HttpCode;
import org.example.computerdesign.exception.ServiceException;
import org.springframework.http.HttpRequest;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;
/**
 * @author 朱文权
 * */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理业务异常
     * */
    @ExceptionHandler(ServiceException.class)
    public RespBody<?> handleServiceException(ServiceException e, HttpServletRequest res){
        String uri = res.getRequestURI();
        log.error("请求地址:{},发生业务异常:{}",uri,e.getMessage());
        e.printStackTrace();
        return RespBody.fail(e);
    }
    @ExceptionHandler(Exception.class)
    public RespBody<?> handleException(Exception e,HttpServletRequest res){
        String uri = res.getRequestURI();
        log.error("请求地址:{},发生系统异常:{}",uri,e.getMessage());
        e.printStackTrace();
        return RespBody.fail(HttpCode.ERROR.getMsg(), HttpCode.ERROR.getCode());
    }
    @ExceptionHandler(RuntimeException.class)
    public RespBody<?> handleRuntimeException(RuntimeException e,HttpServletRequest res){
        String uri = res.getRequestURI();
        log.error("请求地址:{},发生未知异常:{}",uri,e.getMessage());
        e.printStackTrace();
        return RespBody.fail(HttpCode.UNKNOWN_ERROR+":"+e.getMessage(),HttpCode.UNKNOWN_ERROR.getCode());
    }
    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RespBody<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        e.printStackTrace();
        return RespBody.fail( "参数校验异常：" + message,400);
    }
}
